package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/*
    线程任务：
    负责与特定的客户端进行HTTP交互
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            //http://localhost: 8088/

    //1解析请求:
            String line = readLine();
            System.out.println("请求行："+line);

        //请求行相关信息：
            String method;//请求方式
            String url;//抽象路径
            String protocol;//协议版本
            String[] data = line.split("\\s");
            method = data[0];//请求(字符串)地址的请求方式:默认-》GET
            url = data[1];//
            protocol = data[2];
            System.out.println("method:"+method);
            System.out.println("uri:"+url);
            System.out.println("protocol:"+protocol);

        //读消息头：
            Map<String,String> headers = new HashMap<>();//使用了map集合获取消息头
            while (true){
                line = readLine();
                if (line.isEmpty()) {
                //如果读取的是空字符串说明单独读取了CRLF
                    break;
                }
                System.out.println("消息头："+line);
                data = line.split(":\\s");
                headers.put(data[0],data[1]);
            }
            System.out.println("headers："+headers);


    //2处理请求:
    //3发送响应:
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                //响应后断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*重用代码：*/
    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a';//作为本次读取到的字符
        char pre = 'a';//作为上次读取到的子符
        int d;
        while ((d = in.read())!=-1){
            cur = (char)d;//本次读取到的字符
            if (pre==13 && cur==10){
                break;
            }
            builder.append(cur);//
            pre = cur;//下次循环前将本次读取到的字符记为上次读取到的字符
            System.out.print((char)d);
        }
        return builder.toString().trim();
    }
}
